﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;

using System.Text;

namespace System.Data.SugarClient
{
	public class SugarDataAdapter : DbDataAdapter
	{

		#region Constructors

		public SugarDataAdapter() { }

		public SugarDataAdapter(
			DbCommand selectCommand)
		{
			base.SelectCommand = selectCommand;
		}

		public SugarDataAdapter(
			string selectCommandText,
			string sonnectionString)
		{
			_internalConnection = new SugarConnection(sonnectionString);
			_internalConnection.Open();
			base.SelectCommand = new SugarCommand(selectCommandText, _internalConnection);
		}

		#endregion

		#region Events

		public event SugarRowUpdatingEventHandler RowUpdating;
		public event SugarRowUpdatedEventHandler RowUpdated;

		#endregion

		#region Fields

		private SugarConnection _internalConnection;

		#endregion

		protected override void OnRowUpdated(RowUpdatedEventArgs value)
		{
			Trace.Debug("OnRowUpdated");
			base.OnRowUpdated(value);

			try
			{
				ISetEntryActionResult currentresult = (value.Command as SugarCommand).ActionResult as ISetEntryActionResult;
				if (currentresult != null)
				{
					// feedback dbresults
					IGetEntryActionResult result =
						((value.Command as SugarCommand).Connection as SugarConnection).SoapContext.ExecuteAction(
							SugarSoapActionType.GetEntry,
							currentresult.Action.Module,
							currentresult.Id,
							ToStringArray(value.Row.Table.Columns)) as IGetEntryActionResult;
					for (int i = 0; i < result.FieldCount; ++i)
					{
						string fieldname = result.GetFieldNameAt(i);
						if (result[i] != null) value.Row[fieldname] = result[i].ToString();
					}
				}
			}
			catch (Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.Message);
				System.Diagnostics.Debug.WriteLine(ex.StackTrace);
			}

			

			if (value.Errors != null)
			{
				System.Diagnostics.Debug.WriteLine(value.Errors.Message);
				System.Diagnostics.Debug.WriteLine(value.Errors.StackTrace);
			}

			// fire events
			if (this.RowUpdated != null) this.RowUpdated(this, value);
		}

		protected string[] ToStringArray(DataColumnCollection columns)
		{
			List<string> values = new List<string>();
			foreach (DataColumn column in columns) { values.Add(column.ColumnName); }
			return values.ToArray();
		}

		protected override void Dispose(bool disposing)
		{
			base.Dispose(disposing);
			if (_internalConnection != null)
			{
				this._internalConnection.Close();
			}
		}
	}

	public delegate void SugarRowUpdatingEventHandler(
		object sender, RowUpdatingEventArgs e);

	public delegate void SugarRowUpdatedEventHandler(
		object sender, RowUpdatedEventArgs e);

}
